/*pmFWCFu5nhKkBzYmrkBakSV6B6xE5zJS9Xlf9U/PYPi9wdgsReU89OhlkJs/0fgI*/
/*
 * @Author: xiahui
 * @PageInfo: 采购合同卡片模板
 * @Date: 2019-01-10 17:38:56
 * @Last Modified by: zhr
 * @Last Modified time: 2021-09-08 22:44:36
 */

import { ajax } from 'nc-lightapp-front';
import { PAGECODE, AREA, UISTATUS, BUTTONID, FIELDS, URL, CARDTABLEAREAIDS, DEFCACHEKEY } from '../../constance';
import { buttonControl } from '../viewControl/buttonControl';
import pageInfoClick from '../btnClicks/pageInfoClick';
import headAfterEvent from '../afterEvents/headAfterEvent';
import { setCardPageForEmptyPk_org_v, toggleCardTable, getAreaAndBtnId } from '../../utils/cardPageUtil';
import { headReferFilter } from '../referFilter/headReferFilter';
import copyBtnClick from '../btnClicks/copyBtnClick';
import transtypeUtils from '../../../../../scmpub/scmpub/pub/tool/transtypeUtils';
import { lineBtnClick } from '../btnClicks';
import { getLangByResId } from '../../../../../scmpub/scmpub/pub/tool/multiLangUtil';
import { setDefData } from '../../../../../scmpub/scmpub/pub/cache/cacheDataManager';
import { columnSortUtils } from '../../../../../scmpub/scmpub/pub/tool/columnSortUtils';
const { init, getTranstypeID, getTranstypeName, getTranstypeCode } = transtypeUtils;

export default function(props) {
	props.createUIDom(
		{
			pagecode: PAGECODE.cardPagecode
		},
		(data) => {
			if (data) {
				if (data.context) {
					// 发布交易类型处理
					init.call(this, data.context);
					this.contexts = data.context;
				}
				if (data.button) {
					let button = data.button;
					props.button.hideButtonsByAreas([
						AREA.card_head,
						AREA.card_body,
						AREA.card_term,
						AREA.card_fee,
						AREA.card_pay,
						AREA.card_memora
					]); // 隐藏所有按钮
					props.button.setOprationBtnsRenderStatus([ AREA.card_body_inner ], false);

					props.button.setButtons(button);
				}
				if (data.template) {
					let meta = data.template;
					modifierMeta.call(this, props, meta);
					props.meta.setMeta(meta, () => {
						// 设置默认数据
						setDefaultData.call(this, props, data);
						props.cardTable.selectAllRows(AREA.cardTableId, false); // 取消浏览态表体勾选
					});
				}
			}
		}
	);
}

function modifierMeta(props, meta) {
	let status = props.getUrlParam('status');
	meta[AREA.cardFormId].status = status;
	meta[AREA.cardTableId].status = status;
	// 操作列
	[ AREA.cardTableId, AREA.cardTermId, AREA.cardPayId, AREA.cardFeeId, AREA.cardMemoraId ].forEach((moduleId) => {
		meta[moduleId].items.push({
			label: getLangByResId(this, '4004PURDAILY-000050') /* 国际化处理： 操作*/,
			itemtype: 'customer',
			attrcode: 'opr',
			width: '160px',
			visible: true,
			fixed: 'right',
			render: (text, record, index) => {
				if (AREA.cardPayId != moduleId) {
					let { InnerAreaId, InnerBtnIds } = getAreaAndBtnId(
						moduleId,
						props.getUrlParam('status'),
						this.copyLineDatas[moduleId]
					);

					return props.button.createOprationButton(InnerBtnIds, {
						area: InnerAreaId,
						buttonLimit: 3,
						onButtonClick: (props, key) =>
							lineBtnClick.call(this, moduleId, props, key, text, record, index)
					});
				} else {
					if (UISTATUS.modify != props.getUrlParam('status')) {
						let { InnerAreaId, InnerBtnIds } = getAreaAndBtnId(
							moduleId,
							props.getUrlParam('status'),
							this.copyLineDatas[moduleId]
						);

						return props.button.createOprationButton(InnerBtnIds, {
							area: InnerAreaId,
							buttonLimit: 3,
							onButtonClick: (props, key) =>
								lineBtnClick.call(this, moduleId, props, key, text, record, index)
						});
					}
				}
			}
		});
	});

	meta[AREA.cardFormId].items.map((item) => {
		item.isShowUnit = false;
	});

	let fixAssts = [ 'casscustid', 'casscustvid', 'cbprojectid', 'cproductorid', 'cvendorvid', 'cvendorid' ];
	meta[AREA.cardTableId].items.map((item) => {
		item.isShowUnit = false;
		if (item.attrcode.indexOf('vfree') != -1 || fixAssts.includes(item.attrcode)) {
			item.queryCondition = () => {
				let data = props.form.getFormItemsValue(AREA.cardFormId, FIELDS.pk_org).value;
				return { pk_org: data };
			};
		}
	});

	mutiSelectOpt(meta); // 多选配置

	headReferFilter(props, meta, AREA.cardFormId); // 表单参照过滤
	//CARDTABLEAREAIDS.forEach(areaId => {
	//});
	columnSortUtils.numberSort(meta, AREA.cardTableId, FIELDS.crowno);
	return meta;
}

function mutiSelectOpt(meta) {
	let mutiFields = [ FIELDS.pk_material ]; //FIELDS.pk_marbasclass去除物料基本分类多选
	meta[AREA.cardTableId].items.map((item) => {
		if (mutiFields.includes(item.attrcode)) {
			item.isMultiSelectedEnabled = true;
		}
	});
}

function setDefaultData(props, data) {
	let status = props.getUrlParam('status');
	let pk = props.getUrlParam('id');
	//增加推单逻辑，如果推单标识不是价格审批单，逻辑同以前
	let channelType = props.getUrlParam('channelType'); //推单标识
	if (channelType && channelType == 'priceaudit') {
		let tourl = URL.query28toZ2;
		let appcode = this.props.getUrlParam('vsrcAppcode');
		let ids = JSON.parse(this.props.getUrlParam('pushId'));
		let vsrctype = this.props.getUrlParam('vsrctype'); //上游单据类型，用来判断调用哪个接口
		let url = props.getUrlParam('channelAddress');
		this.setState({
			returnURL: '/' + url,
			appcode: appcode,
			returnType: ''
		});
		let data = {
			pks: ids,
			pagecode: PAGECODE.cardPagecode,
			vsrctype: vsrctype
		};

		// 价格审批单推单时，供应商不允许修改
		props.form.setFormItemsDisabled(AREA.cardFormId, {
			[FIELDS.cvendorvid]: true,
			[FIELDS.cvendorid]: true
		});

		ajax({
			method: 'POST',
			url: tourl,
			data: data,
			success: (res) => {
				props.beforeUpdatePage();
				if (res.data) {
					props.transferTable.setTransferListValue(AREA.cardLeftId, res.data);
					//props.resMetaAfterPkorgEdit(); //选择主组织以后，恢复其他字段的编辑性
					//props.form.setFormItemsDisabled(formId, { [SCORDER_CARD.pk_org_v]: true });
				}
				props.updatePage(AREA.cardFormId, [ AREA.cardPayId, AREA.cardTableId ]);
			}
		});
	} else {
		if (status == UISTATUS.add) {
			// 新增
			buttonControl.call(this, props);
			mainOrgInit.call(this, props, data.context);
			setTransType.call(this, props);
		} else if (status == UISTATUS.copy) {
			// 复制
			copyBtnClick.call(this, props, pk);
		} else if (status == UISTATUS.ref20 || status == UISTATUS.ref28) {
			// 转单
			let srcData = props.transferTable.getTransferTableSelectedId(AREA.srcHead);

			let reqData = {
				data: srcData,
				pagecode: PAGECODE.cardPagecode
			};

			if (status == UISTATUS.ref28) {
				// 拉价格审批单时，供应商不允许修改
				props.form.setFormItemsDisabled(AREA.cardFormId, {
					[FIELDS.cvendorvid]: true,
					[FIELDS.cvendorid]: true
				});
			}

			ajax({
				url: status == UISTATUS.ref20 ? URL.queryCard20 : URL.queryCard28,
				data: reqData,
				success: (res) => {
					if (res && res.data) {
						let tranId = getTranstypeID.call(this);
						if (tranId) {
							let tranName = getTranstypeName.call(this);
							let tranCode = getTranstypeCode.call(this);
							res.data.forEach((item) => {
								item.head.head.rows[0].values.ctrantypeid = {
									value: tranId,
									display: tranName
								};
								item.head.head.rows[0].values.vtrantypecode = {
									value: tranCode
								};
							});
						}
						props.transferTable.setTransferListValue(AREA.cardLeftId, res.data);

						if (status == UISTATUS.ref20) {
							// 设置‘已生成订单量作为合同执行’默认值
							let bordernumexec = props.getUrlParam('bordernumexec');
							props.form.setFormItemsValue(AREA.cardFormId, {
								[FIELDS.bordernumexec]: { value: bordernumexec }
							});
						}
					}
				}
			});
		} else if (status == UISTATUS.modify) {
			// 设置'合同类型'不可编辑
			props.form.setFormItemsDisabled(AREA.cardFormId, {
				[FIELDS.ctrantypeid]: true
			});
			pageInfoClick.call(this, props, pk);
		} else {
			pageInfoClick.call(this, props, pk);
		}
	}
	toggleCardTable.call(this, props); // 卡片表体默认收起
	// 设置按钮可用性
	props.button.setButtonDisabled(
		[
			BUTTONID.DeleteLine,
			BUTTONID.DeleteLineTerm,
			BUTTONID.DeleteLinePay,
			BUTTONID.DeleteLineFee,
			BUTTONID.DeleteLineMemora,
			BUTTONID.CopyLine,
			BUTTONID.CopyLineTerm,
			BUTTONID.CopyLinePay,
			BUTTONID.CopyLineFee,
			BUTTONID.CopyLineMemora,
			BUTTONID.LinkPriceInfo
		],
		true
	);
}

/**
 * 默认主组织
 * @param {*} props
 * @param {*} context
 */
function mainOrgInit(props, context) {
	let pk_org_v = context.pk_org_v;
	if (pk_org_v) {
		props.form.setFormItemsDisabled(AREA.cardFormId, { pk_org_v: false });
		headAfterEvent.call(this, props, AREA.cardFormId, FIELDS.pk_org_v, { value: pk_org_v });
	} else {
		setCardPageForEmptyPk_org_v(props);
	}
}

/**
 * 报账平台自制时，需要带入默认交易类型
 * @param {*} props
 */
function setTransType(props) {
	let transtypecode = props.getUrlParam('transtypecode');
	if (transtypecode) {
		let billtypename = props.getUrlParam('billtypename');
		let billtypeid = props.getUrlParam('billtypeid');
		props.form.setFormItemsValue(AREA.cardFormId, {
			[FIELDS.ctrantypeid]: { value: billtypeid, display: billtypename },
			[FIELDS.vtrantypecode]: { value: transtypecode, display: transtypecode }
		});

		setDefData(DEFCACHEKEY.transTypeCacheKey, 'transtypecode', transtypecode);
		setDefData(DEFCACHEKEY.transTypeCacheKey, 'billtypeid', billtypeid);
		setDefData(DEFCACHEKEY.transTypeCacheKey, 'billtypename', billtypename);
	}
}

/*pmFWCFu5nhKkBzYmrkBakSV6B6xE5zJS9Xlf9U/PYPi9wdgsReU89OhlkJs/0fgI*/